package com.hanyxx.thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author layman
 * @date 2021/2/9
 */
public class Demo01 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        //模拟3个线程
        Demo01Thread threadA = new Demo01Thread(lock);
        Demo01Thread threadB = new Demo01Thread(lock);
        Demo01Thread threadC = new Demo01Thread(lock);
        //设置名称
        threadA.setName("线程A");
        threadB.setName("线程B");
        threadC.setName("线程C");
        //启动
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
class Demo01Thread extends Thread{
    private Lock lock;
    //通过构造方法传递锁对象
    public Demo01Thread(Lock lock){
        this.lock = lock;
    }
    @Override
    public void run() {
        //加上锁
        lock.lock();
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName()+" :---:"+i);
        }
        //解开锁
        lock.unlock();
    }
}
